#!/usr/bin/env python
from twisted.web import server, resource
from twisted.internet import reactor
import subprocess
import dbus
import gobject
import avahi


class GridthonServer(resource.Resource):
    """
        A simple class that allows you to publish services

        in a network using http protocol with avahi and twisted
    """
    isLeaf = True

    def __init__(self, name, func):
        resource.Resource.__init__(self)
        self.name = name
        self.func = func

    def render_GET(self, request):
        return str(self.func(10))


def publish(name, func):
    """Publishing a service function

    This function publishes a service with a name and has a function in the top.

    """
    serviceName = "Gridthon %s" % name
    serviceType = "_gridthon._tcp"
    servicePort = 8080
    serviceTXT = name

    subprocess.Popen(["avahi-publish", "-s", serviceName, serviceType,
        str(servicePort), serviceTXT])

    site = server.Site(GridthonServer(name, func))
    reactor.listenTCP(servicePort, site)
    reactor.run()
